﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Planer.Model.Validators;

namespace Planer.Model
{
    public class AccumulationModel
    {
        static AccumulationModel model = null;

        protected AccumulationModel()
        {            
        }

        public static AccumulationModel GetInstance()
        {
            if (model == null)
            {
                model = new AccumulationModel();
            }

            return model;
        }

        public accumulation GetAccumulationByUser(user User)
        {
            var query = from accum in Program.Db.accumulations
                        where accum.user.id == User.id
                        select accum;
            if (query.Count() == 0)
            {
                accumulation acc = new accumulation()
                {
                    balance = 0,
                    create_date = DateTime.Now,
                    modify_date = DateTime.Now,
                    spent = "n",
                    user = User,
                    name = "Резервный фонд"
                };
                Program.Db.AddToaccumulations(acc);
                Program.Db.SaveChanges();
                return acc;
            }
            return query.First();
        }

        public ModelResult SpentMoney(accumulation Accum, float Money)
        {
            if (Accum.balance < Money)
            {
                return new ModelResult("Указанная сумма превышает доступный баланс");
            }
            Accum.balance -= Money;
            Program.Db.SaveChanges();
            return new ModelResult();
        }
    }
}
